package zxj.weixin.mp.controller;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import zxj.weixin.mp.service.CardService;
import zxj.weixin.mp.service.WeixinService;
import zxj.weixin.mp.utils.WeixinUtils;

/**
 * 微信卡券Controller
 * 
 * @author zhuxuejiang
 *
 */
@RestController
@RequestMapping("/weixin/card")
public class CardController {

	@Autowired
	private CardService cardService;

	@Autowired
	private WeixinService weixinService;

	/**
	 * 获取卡券扩展字段cardExt
	 * 
	 * @param params 参数Map
	 * @return 配置信息Map
	 * @throws Exception
	 */
	@PostMapping("/cardExt")
	public Map<String, String> getCardExt(@RequestBody Map<String, String> params) throws Exception {
		if (null == params) {
			return null;
		}

		String appId = params.get("appId");
		String code = params.get("code");
		String cardId = params.get("cardId");
		String outerStr = params.get("outerStr");

		if (StringUtils.isBlank(appId) || StringUtils.isBlank(code) || StringUtils.isBlank(cardId)) {
			return null;
		}

		// 微信网页授权获取access_token
		Map<String, Object> accessTokenMap = weixinService.getWebAuthAccessToken(appId, code);
		if (null == accessTokenMap) {
			return null;
		}

		String openid = (String) accessTokenMap.get("openid");
		if (StringUtils.isBlank(openid)) {
			return null;
		}

		// 获取api_ticket调用卡券相关接口的临时票据
		String apiTicket = cardService.getApiTicket(appId);
		if (StringUtils.isBlank(apiTicket)) {
			return null;
		}

		// 获取卡券扩展字段cardExt
		Map<String, String> cardExtMap = WeixinUtils.getCardExt(appId, cardId, openid, outerStr, null);

		return cardExtMap;
	}

}
